/*
 * Copyright (c) 2011 Shanda Corporation. All rights reserved.
 *
 * Created on 2012-06-11.
 */

package com.whq.knowverywell.task;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import com.whq.knowverywell.business.db.TblConfHandler;
import com.whq.knowverywell.business.http.ConfRequestUtil;
import com.whq.knowverywell.business.model.ConfResult;
import com.whq.knowverywell.update.AppUpdateUtil;
import com.whq.knowverywell.util.AppUtil;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.constant.CfgConstant;

/**
 * 检测app升级Task.
 *
 * @author wanghuaiqiang
 */
public class ChkAppUpdateTask extends AsyncTask<String, String, String> {
    public static final String TAG = ChkAppUpdateTask.class.getSimpleName();
    
    public static final int CHK_UPDATE_TYPE_AUTO 	= 1;
    public static final int CHK_UPDATE_TYPE_MANUL 	= 2;
    
    private Context ctx = null;
    
    private int appVersionCode = 0;
    
    private String appVersionName = "";
    
    private String appApkName = "";
    
    private String appChgLog = "";
    
    // 检查更新的方式
    private int chkUpateType = CHK_UPDATE_TYPE_AUTO;
    
    private boolean showProgressDialog = false;
    
    private ProgressDialog pBar = null;
    
    public ChkAppUpdateTask(Context ctx, int chkUpateType, boolean showProgressDialog) {
        this.ctx = ctx;
        this.chkUpateType = chkUpateType;
        this.showProgressDialog = showProgressDialog;
    }
    
    @Override
	protected void onPreExecute() {
		super.onPreExecute();
		
		if (this.showProgressDialog) {
			pBar = new ProgressDialog(ctx);  
	        pBar.setTitle("正在检查应用版本");  
	        pBar.setMessage("请稍候...");  
	        pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	        pBar.show();
		}
    }

    @Override
    public String doInBackground(String... params) {
    	this.appVersionCode = 0;
    	
    	boolean needChk = false;
    	if (chkUpateType == CHK_UPDATE_TYPE_MANUL) {
    		needChk = true;
    	} else {
    		long now = System.currentTimeMillis();
    		if ( (now - getLastUpateNotifyTime(this.ctx)) > CfgConstant.UPDATE_NOTIFY_INTERVAL_MILLISECOND) {
    			needChk = true;
    		}
    	}
    	
    	LogUtil.i(TAG, "needChk: " + needChk);
    	
    	if (needChk) {
    		setLastUpateNotifyTime(this.ctx, System.currentTimeMillis());
    		LogUtil.i(TAG, "check new version app from server");
    		ConfResult confResult = ConfRequestUtil.getConfFromServer(this.ctx);
        	if (confResult != null) {
        		this.appVersionCode = confResult.getAppVersionCode();
            	this.appVersionName = confResult.getAppVersionName();
            	this.appApkName = confResult.getAppApkName();
            	this.appChgLog = confResult.getAppChgLog();
            	
            	LogUtil.i(TAG, "appVersionCode[" + appVersionCode + "],appVersionName[" + appVersionName + "]");
        	}
    	}
		
        return null;
    }
    
    @Override
    public void onPostExecute(String result) {
    	if (this.pBar != null) {
    		this.pBar.cancel();
    	}
    	if (this.appVersionCode > AppUtil.getVersionCode(this.ctx)) {
    		switch (this.chkUpateType) {
    		case CHK_UPDATE_TYPE_AUTO:
    			LogUtil.i(TAG, "send app update notification");
    			AppUpdateUtil.chkAppUpdateNotification(this.ctx, 
    					this.appVersionCode, this.appVersionName, this.appApkName, this.appChgLog);
    			break;
    		case CHK_UPDATE_TYPE_MANUL:
    			AppUpdateUtil.doNewVersionUpdate(this.ctx, this.appVersionName, this.appApkName, this.appChgLog);
    			break;
    		default:
    			break;
    		}
    	} else {
    		if (this.chkUpateType == CHK_UPDATE_TYPE_MANUL) {
    			Toast.makeText(this.ctx, "您使用的版本已经是最新的了!", Toast.LENGTH_SHORT).show();
    		}
    	}
    }
    
    /**
     * 获取更新notify的时间戳
     * @param context
     * @return
     */
	private long getLastUpateNotifyTime(Context context) {
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		return tblConfHandler.getOneLongConf(TblConfHandler.KEY_LAST_UPDATE_NOTIFY_TIME, 0l);
	}
	
	private void setLastUpateNotifyTime(Context context, long lastTime) {
		TblConfHandler tblConfHandler = new TblConfHandler(context);
		tblConfHandler.saveOneConf(TblConfHandler.KEY_LAST_UPDATE_NOTIFY_TIME, lastTime);
	}
    
}
